package com.wewins.fota.bean.bo.cond;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;

public abstract class StringCond implements Cond {
    @Override
    public boolean check(Object t) {
        if (!(t instanceof String)) {
            return false;
        }
        return this.check((String) t);
    }

    public abstract boolean check(String cond);


    public static StringCond parse(String condStr) {
        StringCond cond;
        if (StringUtils.isEmpty(condStr)) {
            cond = StringListCond.builder().imeiList(new ArrayList<>()).build();
        } else if (!isRangeImei(condStr)) {
            cond = StringListCond.builder().imeiList(Arrays.asList(condStr.split("[,，]"))).build();
        } else {
            String[] items = condStr.substring(1, condStr.length() - 1).split("[,，]");
            if (items.length != 2) {
                cond = StringListCond.builder().imeiList(Arrays.asList(items)).build();
            } else {
                cond = StringRangeCond.builder()
                        .minImei(items[0].trim())
                        .maxImei(items[1].trim())
                        .includeMin(condStr.startsWith("["))
                        .includeMax(condStr.endsWith("]"))
                        .build();
            }
        }
        return cond;
    }

    private static boolean isRangeImei(String condStr) {
        return (condStr.startsWith("[") || condStr.startsWith("(")) && (condStr.endsWith("]") || condStr.endsWith(")"));
    }
}
